<template>
	<view class="page add-friend-page">
		<!-- 自定义导航栏 -->
		 <br>
		<ob-navbar title="添加好友" :show-back="true" />
		<br>
		<view class="content">
			<!-- 搜索区域 -->
			<view class="search-section">
				<view class="search-box">
					<input 
						v-model="searchKeyword"
						type="text" 
						placeholder="输入用户名、邮箱或手机号"
						class="search-input"
						@confirm="handleSearch"
						@input="onSearchInput"
					/>
					<button 
						class="search-btn" 
						:disabled="!searchKeyword.trim() || isSearching"
						@click="handleSearch"
					>
						{{ isSearching ? '搜索中' : '搜索' }}
					</button>
				</view>
			</view>
			
			<!-- 快速添加方式 -->
<!--			<view class="quick-add-section">-->
<!--				<view class="section-header">-->
<!--					<text class="section-title">快速添加</text>-->
<!--				</view>-->
<!--				-->
<!--				<view class="quick-options">-->
<!--					<view class="quick-option" @click="scanQRCode">-->
<!--						<view class="option-icon">Q</view>-->
<!--						<text class="option-title">扫码添加</text>-->
<!--						<text class="option-desc">扫描对方二维码</text>-->
<!--					</view>-->
<!--					-->
<!--					<view class="quick-option" @click="showMyQRCode">-->
<!--						<view class="option-icon">M</view>-->
<!--						<text class="option-title">我的二维码</text>-->
<!--						<text class="option-desc">展示给朋友扫码</text>-->
<!--					</view>-->
<!--					-->
<!--					<view class="quick-option" @click="addFromContacts">-->
<!--						<view class="option-icon">C</view>-->
<!--						<text class="option-title">通讯录好友</text>-->
<!--						<text class="option-desc">从手机通讯录添加</text>-->
<!--					</view>-->
<!--				</view>-->
<!--			</view>-->
			<!-- 搜索结果 -->
			<view v-if="searchResults.length > 0" class="search-results-section">
				<view class="section-header">
					<text class="section-title">搜索结果</text>
				</view>
				
				<view class="search-results">
					<view 
						v-for="user in searchResults" 
						:key="user.id"
						class="user-item"
						@click="viewUserProfile(user)"
					>
						<image 
							:src="getAvatar(user.avatar)"
							class="user-avatar" 
							mode="aspectFill" 
						/>
						<view class="user-info">
							<text class="user-name">{{ user.nickname || user.realName || user.username }}</text>
							<text class="user-desc">{{ user.email || user.phone || user.username }}</text>
						</view>
						<button 
							class="add-btn" 
							:class="{ 'added': user.isFriend, 'friend': user.isFriend }"
							:disabled="user.isFriend || user.requestSent"
							@click.stop="handleUserAction(user)"
						>
							{{ getFriendButtonText(user) }}
						</button>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view v-if="showEmptyState" class="empty-state">
				<ob-empty 
					:image="'/static/images/empty-search.png'"
					title="暂无搜索结果"
					description="尝试输入完整的用户名或邮箱"
				/>
			</view>
			
			<!-- 推荐好友 -->
			<view v-if="recommendedFriends.length > 0" class="recommended-section">
				<view class="section-header">
					<text class="section-title">推荐好友</text>
				</view>
				
				<view class="recommended-list">
					<view 
						v-for="user in recommendedFriends" 
						:key="user.id"
						class="user-item"
						@click="viewUserProfile(user)"
					>
						<image 
							:src="getAvatar(user.avatar)"
							class="user-avatar" 
							mode="aspectFill" 
						/>
						<view class="user-info">
							<text class="user-name">{{ user.nickname || user.realName || user.username }}</text>
							<text class="user-desc">{{ user.mutualFriends ? user.mutualFriends + '个共同好友' : '推荐好友' }}</text>
						</view>
						<button 
							class="add-btn" 
							:class="{ 'friend': user.isFriend }"
							:disabled="user.isFriend || user.requestSent"
							@click.stop="handleUserAction(user)"
						>
							{{ getFriendButtonText(user) }}
						</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 二维码弹窗 -->
		<view v-if="showQRModal" class="qr-modal" @click="showQRModal = false">
			<view class="qr-content" @click.stop>
				<view class="qr-header">
					<text class="qr-title">我的二维码</text>
					<text class="close-btn" @click="showQRModal = false">×</text>
				</view>
				<view class="qr-body">
					<image :src="myQRCode" class="qr-image" mode="aspectFit" />
					<text class="qr-tip">让朋友扫描此二维码添加你为好友</text>
				</view>
			</view>
		</view>
		
		<!-- 好友验证弹窗 -->
		<view v-if="showVerifyModal" class="verify-modal" @click="showVerifyModal = false">
			<view class="verify-content" @click.stop>
				<view class="verify-header">
					<text class="verify-title">发送好友申请</text>
					<text class="close-btn" @click="showVerifyModal = false">×</text>
				</view>
				<view class="verify-body">
					<view class="user-preview">
						<image
							:src="getAvatar(selectedUser?.avatar)"
							class="preview-avatar" 
							mode="aspectFill" 
						/>
						<text class="preview-name">{{ selectedUser?.nickname || selectedUser?.realName || selectedUser?.username }}</text>
					</view>
					<view class="verify-form">
						<text class="form-label">验证信息</text>
						<textarea 
							v-model="verifyMessage"
							placeholder="请输入验证信息，让对方了解你的来意"
							class="verify-input"
							maxlength="100"
							@input="onVerifyInput"
						/>
						<text class="char-count">{{ verifyMessage.length }}/100</text>
					</view>
					<view class="verify-actions">
						<button class="cancel-btn" @click="showVerifyModal = false">取消</button>
						<button class="confirm-btn" :disabled="!verifyMessage.trim()" @click="confirmSendRequest">发送</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import friendApi from '../../api/friend.js'
import { resolveAvatarUrl } from '../../utils/avatar.js'

// 统一头像解析（不使用默认图）
const getAvatar = (url) => resolveAvatarUrl(url || '')

// 响应式数据
const searchKeyword = ref('')
const searchResults = ref([])
const recommendedFriends = ref([])
const isSearching = ref(false)
const isLoading = ref(false)
const showQRModal = ref(false)
const myQRCode = ref('')
const hasSearched = ref(false)
const showVerifyModal = ref(false)
const selectedUser = ref(null)
const verifyMessage = ref('')

// 计算属性
const showEmptyState = computed(() => {
	return hasSearched.value && searchResults.value.length === 0 && !isSearching.value
})

// 生命周期
onMounted(() => {
	loadRecommendedFriends()
	generateMyQRCode()
})

// 方法
const onSearchInput = () => {
	// 如果搜索框为空，清空结果
	if (!searchKeyword.value.trim()) {
		searchResults.value = []
		hasSearched.value = false
		return
	}
	
	// 实时搜索防抖
	clearTimeout(window.searchTimer)
	window.searchTimer = setTimeout(() => {
		if (searchKeyword.value.trim()) {
			handleSearch()
		}
	}, 500)
}

const handleSearch = async () => {
	if (!searchKeyword.value.trim() || isSearching.value) return
	
	try {
		isSearching.value = true
		hasSearched.value = true
		
		const response = await friendApi.searchUsers(searchKeyword.value.trim())

		// 确保response是数组
		const searchData = Array.isArray(response) ? response : (response?.data || [])
		searchResults.value = searchData

		console.log('搜索结果:', response)
		console.log('处理后的搜索数据:', searchData)
		
	} catch (error) {
		console.error('搜索用户失败:', error)
		uni.showToast({
			title: '没有找到该用户呢',
			icon: 'none'
		})
	} finally {
		isSearching.value = false
	}
}

const loadRecommendedFriends = async () => {
	try {
		const response = await friendApi.getRecommendedFriends()
		recommendedFriends.value = response.list || []
	} catch (error) {
		console.error('加载推荐好友失败:', error)
	}
}

const sendFriendRequest = (user) => {
	// 设置选中的用户和默认验证消息
	selectedUser.value = user
	const userInfo = uni.getStorageSync('userInfo')
	verifyMessage.value = `我是 ${userInfo?.nickname || userInfo?.name || '用户'}，想加你为好友`
	
	// 显示验证消息弹窗
	showVerifyModal.value = true
}

const confirmSendRequest = async () => {
	try {
		// 获取当前登录用户信息
		const userInfo = uni.getStorageSync('userInfo')
		const fromUserId = userInfo?.id || userInfo?.userId
		const toUserId = selectedUser.value.id // 接收方用户ID
		
		if (!fromUserId) {
			uni.showToast({
				title: '用户未登录，请重新登录',
				icon: 'none'
			})
			return
		}
		
		console.log('发送好友请求:', {
			fromUserId,
			toUserId,
			message: verifyMessage.value.trim()
		})
		
		await friendApi.sendFriendRequest({
			fromUserId: fromUserId,
			toUserId: toUserId,
			message: verifyMessage.value.trim()
		})
		
		// 更新用户状态
		selectedUser.value.requestSent = true
		
		// 关闭弹窗
		showVerifyModal.value = false
		
		uni.showToast({
			title: '好友请求已发送',
			icon: 'success'
		})
	} catch (error) {
		console.error('发送好友请求失败:', error)
		uni.showToast({
			title: '发送失败',
			icon: 'none'
		})
	}
}

const onVerifyInput = () => {
	// 限制输入长度
	if (verifyMessage.value.length > 100) {
		verifyMessage.value = verifyMessage.value.substring(0, 100)
	}
}

const getFriendButtonText = (user) => {
	if (user.isFriend) return '已经是好友了'
	if (user.requestSent) return '已发送待通过'
	if (user.canResend) return '重新添加'
	return '添加'
}

const handleUserAction = (user) => {
	if (user.isFriend) {
		// 已是好友，不做任何操作
		return
	}
	if (user.requestSent) {
		// 已发送申请，不做任何操作
		return
	}
	if (user.canAdd || user.canResend) {
		// 可以添加或重新添加
		sendFriendRequest(user)
	}
}

const viewUserProfile = (user) => {
	uni.navigateTo({
		url: `/pages/profile/user?userId=${user.id}`
	})
}

const scanQRCode = () => {
	uni.scanCode({
		success: (res) => {
			// 处理扫码结果
			console.log('扫码结果:', res.result)
			// 这里应该解析二维码内容并添加好友
			uni.showToast({
				title: '正在添加好友...',
				icon: 'loading'
			})
		},
		fail: (error) => {
			console.error('扫码失败:', error)
			uni.showToast({
				title: '扫码失败',
				icon: 'none'
			})
		}
	})
}

const showMyQRCode = () => {
	showQRModal.value = true
}

const generateMyQRCode = async () => {
	try {
		const response = await friendApi.getMyQRCode()
		myQRCode.value = response.qrCodeUrl
	} catch (error) {
		console.error('获取二维码失败:', error)
	}
}

const addFromContacts = () => {
	uni.showModal({
		title: '访问通讯录',
		content: '需要访问您的通讯录来查找好友，是否允许？',
		success: (res) => {
			if (res.confirm) {
				// 这里应该调用通讯录API
				uni.showToast({
					title: '功能开发中',
					icon: 'none'
				})
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.add-friend-page {
	background: #FAFAFA;
	min-height: 100vh;
}

.content {
	padding: 0;
}

.search-section {
	background: #FFFFFF;
	padding: 20px;
	margin: 15px;
	border-radius: 8px;
}

.search-box {
	display: flex;
	gap: 10px;
	align-items: center;
}

.search-input {
	flex: 1;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 6px;
	padding: 12px 15px;
	font-size: 14px;
	height: 44px;
	box-sizing: border-box;
}

.search-btn {
	background: #495057;
	color: #FFFFFF;
	border: none;
	border-radius: 6px;
	padding: 12px 24px;
	font-size: 14px;
	height: 44px;
	min-width: 80px;
	flex-shrink: 0;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&:disabled {
		background: #CED4DA;
		color: #6C757D;
	}
}

.quick-add-section,
.search-results-section,
.recommended-section {
	background: #FFFFFF;
	margin: 15px;
	border-radius: 8px;
	overflow: hidden;
}

.section-header {
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
}

.quick-options {
	padding: 10px 20px;
}

.quick-option {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.option-icon {
	width: 40px;
	height: 40px;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	font-weight: 600;
	color: #6C757D;
	margin-right: 15px;
}

.option-title {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
	margin-bottom: 2px;
}

.option-desc {
	font-size: 12px;
	color: #999999;
}

.search-results,
.recommended-list {
	padding: 0 20px;
}

.user-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.user-avatar {
	width: 50px;
	height: 50px;
	border-radius: 25px;
	margin-right: 12px;
}

.user-info {
	flex: 1;
	min-width: 0;
}

.user-name {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
	display: block;
	margin-bottom: 4px;
}

.user-desc {
	font-size: 12px;
	color: #999999;
}

.add-btn {
	background: #495057;
	color: #FFFFFF;
	border: none;
	border-radius: 4px;
	padding: 8px 16px;
	font-size: 12px;
	
	&:disabled,
	&.added {
		background: #E9ECEF;
		color: #6C757D;
	}
	
	&.friend {
		background: #F8F9FA;
		color: #6C757D;
		border: 1px solid #E9ECEF;
		cursor: default;
		font-weight: 500;
	}
}

.empty-state {
	padding: 50px 20px;
	text-align: center;
}

.qr-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.qr-content {
	background: #FFFFFF;
	border-radius: 12px;
	margin: 0 40px;
	max-width: 300px;
	width: 100%;
}

.qr-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
}

.qr-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
}

.close-btn {
	font-size: 24px;
	color: #999999;
	width: 30px;
	text-align: center;
}

.qr-body {
	padding: 20px;
	text-align: center;
}

.qr-image {
	width: 200px;
	height: 200px;
	margin-bottom: 15px;
}

.qr-tip {
	font-size: 14px;
	color: #666666;
}

.verify-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1001;
	display: flex;
	align-items: center;
	justify-content: center;
}

.verify-content {
	background: #FFFFFF;
	border-radius: 12px;
	margin: 0 30px;
	max-width: 350px;
	width: 100%;
}

.verify-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
}

.verify-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
}

.verify-body {
	padding: 20px;
}

.user-preview {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 20px;
	padding: 15px;
	background: #F8F9FA;
	border-radius: 8px;
}

.preview-avatar {
	width: 60px;
	height: 60px;
	border-radius: 30px;
	margin-bottom: 8px;
}

.preview-name {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
}

.verify-form {
	position: relative;
}

.form-label {
	font-size: 14px;
	color: #333333;
	font-weight: 500;
	display: block;
	margin-bottom: 8px;
}

.verify-input {
	width: 100%;
	min-height: 80px;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 6px;
	padding: 12px;
	font-size: 14px;
	color: #333333;
	resize: none;
	box-sizing: border-box;
	line-height: 1.4;
	
	&:focus {
		border-color: #495057;
		outline: none;
	}
}

.char-count {
	font-size: 12px;
	color: #999999;
	text-align: right;
	display: block;
	margin-top: 5px;
}

.verify-actions {
	display: flex;
	gap: 10px;
	margin-top: 20px;
}

.cancel-btn,
.confirm-btn {
	flex: 1;
	height: 44px;
	border: none;
	border-radius: 6px;
	font-size: 14px;
	cursor: pointer;
}

.cancel-btn {
	background: #F8F9FA;
	color: #6C757D;
	border: 1px solid #E9ECEF;
	
	&:active {
		background: #E9ECEF;
	}
}

.confirm-btn {
	background: #495057;
	color: #FFFFFF;
	
	&:disabled {
		background: #CED4DA;
		color: #6C757D;
		cursor: not-allowed;
	}
	
	&:not(:disabled):active {
		background: #343A40;
	}
}
</style>